package com.hykj.coca.config;

import com.alibaba.fastjson.JSON;
import com.hykj.coca.model.AdminModel;
import com.hykj.coca.result.AppBack;
import com.hykj.coca.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.hykj.coca.utils.Util.returnJson;

/**
 * Created by Administrator on 2017/5/22 0022.
 */
@Component
public class WebInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(WebInterceptor.class);
    @Autowired
    AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        Object adminModel = request.getSession().getAttribute("adminModel");

        if (adminModel == null || !(adminModel instanceof AdminModel)) {
            response.sendRedirect(request.getContextPath() + "/login.html");
            returnJson(response, JSON.toJSONString(new AppBack(-98, "登录过期")));
            return false;
        }
        AdminModel adminModel1= (AdminModel) adminModel;



        if(adminModel1.getStatus()<0){
            response.sendRedirect(request.getContextPath() + "/login.html");
            returnJson(response, JSON.toJSONString(new AppBack(-98, "已被冻结")));
            return false;
        }
        return true;
    }




    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}